package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.commom.Constant;
import com.itheima.reggie.commom.CustomException;
import com.itheima.reggie.commom.JwtUtil;
import com.itheima.reggie.commom.SmsTemplate;

import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sendMsg(String phone) {
        // 1.生成6位随机数
        String code = RandomUtil.randomString(6);
        code="123";
        // 2.发送短信
//      smsTemplate.sendSms(phone,code);
        log.info("发送短信成功：{}",code);
        // 3.redis存储一份验证码，有效期5分钟
        redisTemplate.opsForValue().set(Constant.USER_CODE+phone,code, Duration.ofSeconds(300));


    }

    @Override
    public String login(String phone, String code) {
        // 1.校验验证码
        // 1-1 取出redis中验证码
        String codeRedis = (String) redisTemplate.opsForValue().get(Constant.USER_CODE + phone);
        // 1-2 比较
        if (!StrUtil.equals(code,codeRedis)) { //  不一致
            throw new CustomException("验证码不正确");
        }

        // 2.根据phone查询数据库  select * from user where phone = ?
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        User user = userMapper.selectOne(qw);

        // 3.没查到，创建新用户
        if (user == null) {
            user = new User();
            user.setPhone(phone); // 手机号
            user.setStatus(1); // 正常
            // 保存数据库
            userMapper.insert(user);
        }
        // 4.老用户，制作token
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);

        // 5.删除redis验证码
        redisTemplate.delete(Constant.USER_CODE + phone);

        // 6.返回token
        return token;
    }


}
